const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

// 定义 User 模型
const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: 'User ID'
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    validate: {
      notNull: {
        msg: 'Name cannot be empty'
      },
      notEmpty: {
        msg: 'Name cannot be empty'
      }
    },
    comment: 'Name'
  },
  username: {
    type: DataTypes.STRING(30),
    allowNull: false,
    unique: {
      msg: 'Username already exists'
    },
    validate: {
      notNull: {
        msg: 'Username cannot be empty'
      },
      notEmpty: {
        msg: 'Username cannot be empty'
      }
    },
    comment: 'Username'
  },
  password: {
    type: DataTypes.STRING(255),
    allowNull: false,
    validate: {
      notNull: {
        msg: 'Password cannot be empty'
      },
      notEmpty: {
        msg: 'Password cannot be empty'
      }
    },
    comment: 'Password'
  }
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

// 实例方法：比较密码（不加密，直接比较）
User.prototype.comparePassword = function(candidatePassword) {
  return this.password === candidatePassword;
};

// 重写 toJSON 方法，自动隐藏密码
User.prototype.toJSON = function() {
  const values = { ...this.get() };
  delete values.password;
  return values;
};

module.exports = User;
